package net.moao.netutils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import net.moao.netutils.customView.HeadersEditDialogFragment;
import net.moao.netutils.databinding.ActivityHttpBinding;
import net.moao.netutils.utils.MapUtils;
import net.moao.netutils_library.http.HttpRequest;
import net.moao.netutils.utils.AlertDialogUtils;
import net.moao.netutils.utils.AppConfig;
import net.moao.netutils_library.http.HttpResponse;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HttpActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "HttpActivity";
    public enum LocalStorageField {
        HTTP_URL(TAG + "_HttpUrl"),
        REQUEST_HEADERS_KEY(TAG + "_RequestHeadersKeySetString"),
        REQUEST_HEADERS_VALUE(TAG + "_RequestHeadersValueSetString"),
        REQUEST_BODY(TAG + "_RequestBody");

        private final String fieldName;

        LocalStorageField(String fieldName) {
            this.fieldName = fieldName;
        }

        public String getFieldName() {
            return fieldName;
        }

        @Override
        public String toString() {
            return fieldName;
        }
    }
    Activity mActivity;
    ActivityHttpBinding binding;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHttpBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mActivity = this;
        binding.btnCloseWindow.setOnClickListener(this);
        binding.btnSettingHeaders.setOnClickListener(this);
        binding.btnSettingContent.setOnClickListener(this);
        binding.btnGET.setOnClickListener(this);
        binding.btnPOST.setOnClickListener(this);
        binding.btnPUT.setOnClickListener(this);
        binding.btnDELETE.setOnClickListener(this);
        binding.btnHEAD.setOnClickListener(this);
        binding.btnOPTIONS.setOnClickListener(this);
        binding.btnPATCH.setOnClickListener(this);
        binding.btnCONNECT.setOnClickListener(this);
        binding.btnTRACE.setOnClickListener(this);
        binding.msg.setMovementMethod(ScrollingMovementMethod.getInstance());

        binding.etUrl.setText(AppConfig.getString(mActivity, LocalStorageField.HTTP_URL.getFieldName(), "http://ip.3322.net"));
    }

    @Override
    public void onClick(View view) {
        String url = binding.etUrl.getText().toString();
        AppConfig.putString(mActivity, LocalStorageField.HTTP_URL.getFieldName(), url);
        boolean withHeaders = binding.swWithHeaders.isChecked();
        boolean withBody = binding.swWithBody.isChecked();
        Map<String, String> headers = withHeaders ? MapUtils.createMapFromSets(AppConfig.getStringSet(mActivity, LocalStorageField.REQUEST_HEADERS_KEY.getFieldName()), AppConfig.getStringSet(mActivity, LocalStorageField.REQUEST_HEADERS_VALUE.getFieldName())): null;
        String requestBody = withBody ? AppConfig.getString(mActivity, LocalStorageField.REQUEST_BODY.getFieldName()) : null;

        if (view.getId() == binding.btnCloseWindow.getId()){
            finish();
        } else if (view.getId() == binding.btnSettingHeaders.getId()){
            HeadersEditDialogFragment dialogFragment = new HeadersEditDialogFragment(mActivity);
            dialogFragment.show(getSupportFragmentManager(), " 编辑请求头(Headers)");
        } else if (view.getId() == binding.btnSettingContent.getId()){
            AlertDialogUtils.BtnOnclickListener btnOnclickListener = new AlertDialogUtils.BtnOnclickListener() {
                @Override
                public void BtnConformOnclickListener(DialogInterface dialogInterface, int i, String inputText) {
                    AppConfig.putString(mActivity, LocalStorageField.REQUEST_BODY.getFieldName(), inputText);
                    showMsg("请求体 设置成功, 请求体 为: " + AppConfig.getString(mActivity, LocalStorageField.REQUEST_BODY.getFieldName()));
                }

                @Override
                public void BtnCancelOnclickListener(DialogInterface dialogInterface, int i, String inputText) {
                    showMsg("取消设置请求体, 请求体 为: " + AppConfig.getString(mActivity, LocalStorageField.REQUEST_BODY.getFieldName()));
                }
            };
            AlertDialogUtils.showCreateAlertDialogWithInput(mActivity, "请设置请求体(Body)", AppConfig.getString(mActivity, LocalStorageField.REQUEST_BODY.getFieldName()), getResources().getColor(R.color.colorPrimaryBackground), getResources().getColor(R.color.colorPrimary), R.drawable.ic_launcher_background, "确认", "取消", btnOnclickListener);
        } else if (view.getId() == binding.btnGET.getId()){
            new Thread(()->{
                // 发起 GET 请求
                try {
                    HttpResponse response = HttpRequest.sendGetRequest(url, headers);
                    showMsg(response.toJsonString());
                } catch (Exception e) {
                    Log.e(TAG, "onClick: ", e);
                    showMsg("报错:" + e);
                }
            }).start();
        } else if (view.getId() == binding.btnPOST.getId()){
            new Thread(()->{
                // 发起 POST 请求
                try {
                    HttpResponse response = HttpRequest.sendPostRequest(url, headers, requestBody);
                    showMsg(response.toJsonString());
                } catch (Exception e) {
                    Log.e(TAG, "onClick: ", e);
                    showMsg("报错:" + e);
                }
            }).start();
        } else if (view.getId() == binding.btnPUT.getId()){
            new Thread(()->{
                // 发起 PUT 请求
                try {
                    HttpResponse response = HttpRequest.sendPutRequest(url, headers, requestBody);
                    showMsg(response.toJsonString());
                } catch (Exception e) {
                    Log.e(TAG, "onClick: ", e);
                    showMsg("报错:" + e);
                }
            }).start();
        } else if (view.getId() == binding.btnDELETE.getId()){
            new Thread(()->{
                // 发起 DELETE 请求
                try {
                    HttpResponse response = HttpRequest.sendDeleteRequest(url, headers, requestBody);
                    showMsg(response.toJsonString());
                } catch (Exception e) {
                    Log.e(TAG, "onClick: ", e);
                    showMsg("报错:" + e);
                }
            }).start();
        } else {
            Toast.makeText(mActivity, "敬请期待", Toast.LENGTH_SHORT).show();
        }
    }



    /**
     * 消息提示框 追加内容 自动滚动到底部
     * @param msg 要提示的信息
     */
    public void showMsg(String msg){
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
        Date date = new Date();
        String formattedDate = formatter.format(date);
        runOnUiThread(()->{
            // Tv 追加内容
            binding.msg.append(formattedDate + "：" + msg + "\n\n");
            // 自动滚动
            int offset=binding.msg.getLineCount()*binding.msg.getLineHeight();
            if(offset>binding.msg.getHeight()){
                binding.msg.scrollTo(0,offset-binding.msg.getHeight());
            }
        });
    }
}